'use strict';
const Service = require('egg').Service;
const moment = require('moment');
class AdService extends Service {

  // 新增广告
  async addAd(data) {

    // 如果是绑定商品，则查询该商品上是否绑定了广告
    if (data.link_type === 0 && data.goods_id) {
      const qRes = await this.app.mysql.get('ad', {
        goods_id: data.goods_id,
      });
      if (qRes) {
        return {
          code: 1,
        };
      }
    }
    const res = await this.app.mysql.insert('ad', data);
    console.log('res:', res);
    if (res.affectedRows === 1) {
      return {
        code: 0,
        data: res.insertedId,
      };
    }
    return {
      code: -1,
    };

  }
  async getAdList(data) {
    const page = +data.page || 1;
    const size = +data.size || 10;
    const start = (page - 1) * size;
    const end = page * size;
    const res = await this.app.mysql.query(`select * from ad where is_delete = 0 limit ${start} , ${end}`);
    const total = (await this.app.mysql.select('ad', { where: { is_delete: 0 } })).length;

    res.forEach(item => {
      item.end_time = moment.unix(item.end_time).format('YYYY-MM-DD HH:mm:ss');
    });
    return {
      page,
      total,
      list: res,
    };
  }
  // 更新
  async updateAd(data) {
    console.log('updateAd data:', data);
    const res = await this.app.mysql.update('ad', data);
    if (res.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };
  }
  // 根据id获取
  async getAdById(id) {
    const res = await this.app.mysql.get('ad', { id });
    return res;
  }
  // 删除广告
  async deleteAd(id) {
    const res = await this.app.mysql.delete('ad', { id });
    if (res.affectedRows === 1) {
      return {
        code: 0,
      };
    }
    return {
      code: -1,
    };
  }
}
module.exports = AdService;
